/*
*
*  用户数据模型
*  负责用户部分数据
*
*/
const fs = require('fs');
const path = require('path');
// 导入数据文件
const db = require('../../config/db')

// 引入jwt token工具
const JwtUtil = require('../../utils/jwt')
// 引入处理加解密文件
// const aes = require('../../utils/aes')
// const bcrypt = require('bcryptjs')
const aes2 = require('../../utils/aes2')
// 引入全局文件
const config = require('../../config/default')
// 记录服务器地址
const HOSTURL = `${config.PROTOCOL}://${config.HOST}:${config.PORT}`
// 正则表达式
const rep_phone = /^1[3-9]\d{9}$/
const rep_email = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/


// 删除用户时移除该用户所有的关联内容
const removeAllUserInfo = (user_id) => {
    // 删除收藏内容
    db.query("select * from db_collect_content where user_id='" + user_id + "'", (err, rows) => {
        if (err) {
            resolve({ code: -1, msg: '查询收藏内容名称失败。xxx' })
        } else {
            db.query("delete from  db_collect_content where user_id='" + user_id + "'", function (err, rows) {
                if (err) {
                    console.log({ code: -1, msg: '删除收藏内容失败。' })
                }
            })
        }
    })

    // 删除签到
    db.query("select * from db_signin2 where user_id='" + user_id + "'", (err, rows) => {
        if (err) {
            resolve({ code: -1, msg: '查询签到失败。xxx' })
        } else {
            db.query("delete from  db_signin2 where user_id = '" + user_id + "'", function (err, rows) {
                if (err) {
                    console.log({ code: -1, msg: '删除签到失败。' })
                }
            })
        }
    })

    // 删除收藏题目
    db.query("select * from db_collect_topic where user_id='" + user_id + "'", (err, rows) => {
        if (err) {
            resolve({ code: -1, msg: '查询收藏题目失败。xxx' })
        } else {
            db.query("delete from  db_collect_topic where user_id='" + user_id + "'", function (err, rows) {
                if (err) {
                    console.log({ code: -1, msg: '删除收藏题目失败。' })
                }
            })
        }
    })

    // 删除文章评论
    db.query("select * from db_comment_article where from_user_id='" + user_id + "'", (err, rows) => {
        if (err) {
            resolve({ code: -1, msg: '查询评论失败。xxx' })
        } else {
            db.query("delete from  db_comment_article where from_user_id = '" + user_id + "'", function (err, rows) {
                if (err) {
                    console.log({ code: -1, msg: '删除评论失败。' })
                }
            })

        }
    })
}



// 导出处理用户数据的方法
module.exports = {
    // 编写用户注册方法1
    // 参数：user_id, user_name, user_password, user_email, user_create_time
    register(user_id, user_name, user_password, user_email, user_create_time) {
        console.log({ user_id, user_name, user_password, user_email, user_create_time })
        let user_check_sql = 'select * from db_user where user_email="' + user_email + '"';
        let pwd = aes2.aesEncrypt(user_password)//加密
        let user_insert_sql = 'insert into db_user(user_name,user_password,user_id,user_email,user_create_time) values("' + user_name + '","' + pwd + '","' + user_id + '","' + user_email + '","' + user_create_time + '")';
        return new Promise((resolve, reject) => {
            // 查询用户表
            db.query(user_check_sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询用户失败。',
                        err
                    })
                } else {
                    // 解构赋值(数据库)
                    if (rows.length != 0) {
                        resolve({
                            code: 201,
                            msg: '该用户已存在。'
                        })
                    }
                    else {
                        // 添加用户
                        db.query(user_insert_sql, (err) => {
                            if (err) {
                                resolve({
                                    code: -1,
                                    msg: '注册用户失败。'
                                })
                            } else {
                                resolve({
                                    code: 200,
                                    msg: '恭喜您,注册成功。',
                                    user_name
                                })
                            }
                        })
                    }
                }
            })
        })
    },

    // 编写用户注册方法2（邮箱验证）
    // 参数：user_id, user_name, user_password, user_email, user_create_time, code
    addUser(user_id, user_name, user_password, user_email, user_create_time, code) {
        let user_check_sql = 'select * from db_user where user_email="' + user_email + '"';
        let pwd = aes2.aesEncrypt(user_password)//加密 如123123 加密后是 $2a$10$pt6AsnQ0fSuXY8ugsHSVbOvtRdEorr0j1MHjaEyAdCnEpH7aPseya
        let user_insert_sql = 'insert into db_user(user_name,user_password,user_id,user_email,user_create_time) values("' + user_name + '","' + pwd + '","' + user_id + '","' + user_email + '","' + user_create_time + '")';
        return new Promise((resolve, reject) => {
            const addUser = () => {
                // 查询用户表
                db.query(user_check_sql, (err, rows) => {
                    if (err) {
                        resolve({
                            code: -1,
                            msg: '查询用户失败。'
                        })
                    } else {
                        // 解构赋值(数据库)
                        if (rows.length != 0) {
                            resolve({
                                code: 201,
                                msg: '该用户已存在。'
                            })
                        }
                        else {
                            // 添加用户
                            db.query(user_insert_sql, (err) => {
                                if (err) {
                                    resolve({
                                        code: -1,
                                        msg: '注册用户失败。'
                                    })
                                } else {
                                    resolve({
                                        code: 200,
                                        msg: '恭喜您,注册成功。'
                                    })
                                }
                            })
                        }
                    }
                })
            }
            if (code) {
                let code_check_sql = 'select * from db_code where v1 = "' + code + '"'
                db.query(code_check_sql, (err, rows) => {
                    if (err) {
                        resolve({
                            code: 400,
                            msg: '验证码不存在。'
                        })
                    } else {
                        if (rows.length != 0) {
                            // 判断验证码是否冲突
                            let arr = [...rows].filter(item => {
                                if (item.v1 == code) {
                                    return item;
                                }
                            })
                            if (arr.length == 1) {
                                let sql = 'select * from db_code where v1 = "' + code + '" and code_id = "' + arr[0].code_id + '"';
                                db.query(sql, (err, rows) => {
                                    if (err) {
                                        resolve({
                                            code: -1,
                                            msg: '邮箱验证失败。'
                                        })
                                    } else {
                                        // 验证通过 , 再注册
                                        addUser();
                                    }
                                })
                            } else {
                                resolve({
                                    code: -1,
                                    msg: '验证码冲突了，请重新发送。'
                                })
                            }
                        } else {
                            resolve({
                                code: -1,
                                msg: '验证码错误。'
                            })
                        }
                    }
                })
            } else {
                resolve({
                    code: 400,
                    msg: '请发送邮箱验证码。'
                })
            }
        })
    },

    // 编写用户登录方法
    // 参数：user_account, user_password
    login(user_account, user_password) {
        // console.log({user_account,user_password})
        return new Promise((resolve, reject) => {
            // 查询用户表sql语句
            let user_check_sql = ''
            // 判断用户输入的是邮箱还是手机
            if (rep_email.test(user_account)) {
                user_check_sql = 'select * from db_user where user_email="' + user_account + '"';
            }
            else
                if (rep_phone.test(user_account)) {
                    user_check_sql = 'select * from db_user where user_phone = "' + user_account + '"';
                }
            db.query(user_check_sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '账号或密码错误0'
                    })
                } else {
                    if (rows.length == 1) {
                        // 匹配密码
                        if (aes2.aesDecrypt(user_password, rows[0]['user_password'])) {
                            let [{ user_id, user_name, user_email, user_phone, user_avatar }] = rows
                            // 将用户id传入并生成token
                            let jwt = new JwtUtil(user_id)
                            // 获取token
                            let token = jwt.generateToken()
                            // 定义用户对象
                            var user = {
                                code: 200,
                                msg: '恭喜您,登录成功。',
                                token,
                                user_name,
                                user_email,
                                user_avatar
                            }
                            if (user_phone) {
                                user['user_phone'] = user_phone
                            }
                            // 将 token 等信息反馈给客户端
                            resolve(user)
                        } else {
                            resolve({
                                code: -1,
                                msg: '账号或密码错误1'
                            })
                        }
                    }
                    else if (rows.length == 0) {
                        resolve({
                            code: -1,
                            msg: '账号不存在。'
                        })
                    }
                    else {
                        resolve({
                            code: 500,
                            msg: '系统异常。'
                        })
                    }
                }
            })
        })
    },

    // 编写删除用户方法
    // 参数：user_id, code
    remove(user_id, code) {
        return new Promise((resolve, reject) => {
            // 校验邮箱验证码
            db.query('select * from db_code where v1 = "' + code + '"', (err, rows) => {
                if (err) {
                    resolve({
                        code: 500,
                        msg: '服务端异常。'
                    })
                } else {
                    if (rows.length != 0) {
                        // 判断验证码是否冲突
                        let arr = [...rows].filter(item => {
                            if (item.v1 == code) {
                                return item;
                            }
                        })
                        if (arr.length == 1) {
                            db.query('select * from db_code where v1 = "' + code + '" and code_id = "' + arr[0].code_id + '"', (err, rows) => {
                                if (err) {
                                    resolve({
                                        code: -1,
                                        msg: '邮箱验证失败。'
                                    })
                                } else {
                                    // 验证通过 , 再删除
                                    db.query('delete from db_user where user_id = "' + user_id + '"', function (err) {
                                        if (err) {
                                            resolve({
                                                code: -1,
                                                msg: '删除账号失败。'
                                            })
                                        } else {
                                            //删除用户关联的记录
                                            removeAllUserInfo(user_id);

                                            resolve({
                                                code: 200,
                                                msg: '删除账号成功。'
                                            })
                                        }
                                    })
                                }
                            })
                        } else {
                            resolve({
                                code: -1,
                                msg: '验证码冲突了，请重新发送。'
                            })
                        }
                    } else {
                        resolve({
                            code: -1,
                            msg: '验证码错误。'
                        })
                    }
                }
            })

        })
    },
    // 参数：user_id, code
    delete(user_id) {
        return new Promise((resolve, reject) => {
            db.query('delete from db_user where user_id = "' + user_id + '"', function (err) {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '删除账号失败。'
                    })
                } else {
                    //删除用户关联的记录
                    removeAllUserInfo(user_id);
                    resolve({
                        code: 200,
                        msg: '删除账号成功。'
                    })
                }
            })
        })
    },
    // 编写修改密码方法
    // 参数：user_id, new_password
    update(user_id, new_password) {
        return new Promise((resolve, reject) => {
            let user_check_sql = 'select * from db_user where user_id = "' + user_id + '"'
            db.query(user_check_sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询用户失败。'
                    })
                } else {
                    if (rows.length != 0) {
                        let pwd = aes2.aesEncrypt(new_password)
                        let user_update_sql = 'update db_user set user_password = "' + pwd + '" where user_id="' + user_id + '"';
                        db.query(user_update_sql, function (err) {
                            if (err) {
                                resolve({ code: -1, msg: "修改密码失败。" });
                            } else {
                                resolve({ code: 200, msg: "修改密码成功。" });
                            }
                        });
                    }

                }
            })
        })
    },

    // 设置填写用户信息
    set_info(user_id, user_name,user_phone,user_address,user_age,user_sex,user_school){
        // console.log(user_id, user_name,user_phone,user_address,user_age,user_sex,user_school)
        return new Promise((resolve, reject) => {
            let user_check_sql = 'select * from db_user where user_id = "' + user_id + '"'
            db.query(user_check_sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询用户失败。'
                    })
                } else {
                    if (rows.length != 0) {
                        let user_update_sql = 'update db_user set user_name = "' + user_name + '", user_phone = "' + user_phone + '", user_address = "' + user_address + '", user_age = "' + user_age + '", user_sex = "' + user_sex + '", user_school = "' + user_school + '" where user_id="' + user_id + '"';
                        db.query(user_update_sql, function (err) {
                            if (err) {
                                resolve({ code: -1, msg: "修改用户信息失败。" });
                            } else {
                                resolve({ code: 200, msg: "修改用户信息成功。" });
                            }
                        });
                    }

                }
            })
        })
    },
    // 编写修改头像方法
    // 参数：user_id, avatar
    modify(user_id, avatar) {
        return new Promise((resolve, reject) => {
            db.query("select * from db_user where user_id='" + user_id + "'", (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询用户失败。'
                    })
                } else {
                    if (rows.length != 0) {
                        db.query("update db_user set user_avatar = '" + avatar + "' where  user_id = '" + user_id + "'", function (err, rows) {
                            if (err) {
                                resolve({
                                    code: -1,
                                    msg: "修改头像失败。"
                                });
                            } else {
                                resolve({
                                    code: 200,
                                    msg: "修改头像成功。",
                                    avatar: avatar
                                })
                            }
                        })
                    }
                }
            })
        })
    },

    // 编写找回密码（邮箱验证）
    verify(user_email, code) {
        return new Promise((resolve, reject) => {
            let code_check_sql = 'select * from db_code where v1 = "' + code + '"'
            db.query(code_check_sql, (err, rows) => {
                if (err) {
                    resolve({
                        code: 400,
                        msg: '验证码不存在。'
                    })
                } else {
                    if (rows.length != 0) {
                        // 判断验证码是否冲突
                        let arr = [...rows].filter(item => {
                            if (item.v1 == code) {
                                return item;
                            }
                        })
                        if (arr.length == 1) {
                            let sql = 'select * from db_code where v1 = "' + code + '" and code_id = "' + arr[0].code_id + '"';
                            db.query(sql, (err, rows) => {
                                if (err) {
                                    resolve({
                                        code: -1,
                                        msg: '邮箱验证失败。'
                                    })
                                } else {
                                    db.query('select * from db_user where user_email="' + user_email + '"', (error, result) => {
                                        if (error) {
                                            resolve({
                                                code: -1,
                                                msg: '查询用户失败。'
                                            })
                                        } else {
                                            if (result.length == 1) {
                                                // 将用户id传入并生成token
                                                let jwt = new JwtUtil(result[0].user_id)
                                                // 获取token
                                                let token = jwt.generateToken()
                                                resolve({
                                                    code: 200,
                                                    msg: '邮箱验证通过。',
                                                    token,
                                                    email: result[0].user_email
                                                })
                                            } else {
                                                resolve({
                                                    code: -1,
                                                    msg: '该用户不存在。'
                                                })
                                            }
                                        }
                                    })
                                }
                            })
                        } else {
                            resolve({
                                code: -1,
                                msg: '验证码冲突了，请重新发送。'
                            })
                        }
                    } else {
                        resolve({
                            code: -1,
                            msg: '验证码错误。'
                        })
                    }
                }
            })
        })
    },
    // 参数：user_email, code, new_password
    findpwd(user_email, new_password, user_id) {
        return new Promise((resolve, reject) => {
            // 验证通过 , 重置密码
            // 查询用户表
            db.query('select * from db_user where user_email="' + user_email + '"', (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询用户失败。'
                    })
                } else {
                    // 解构赋值(数据库)
                    // 修改密码
                    let pwd = aes2.aesEncrypt(new_password)
                    let user_update_sql = 'update db_user set user_password = "' + pwd + '" where user_id="' + user_id + '"';
                    db.query(user_update_sql, function (err) {
                        if (err) {
                            resolve({ code: -1, msg: "重置密码失败。" });
                        } else {
                            resolve({ code: 200, msg: "重置密码成功。" });
                        }
                    });
                }
            })
        })
    },
    // 编写用户分页列表方法
    // 参数：page_num,page_size
    items(page_num, page_size) {
        // console.log({page_num,page_size})
        return new Promise((resolve, reject) => {
            // const params = [(parseInt(page_num) - 1) * parseInt(page_size), parseInt(page_size)]
            let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size))
            let page_size2 = (parseInt(page_size))
            let sql = "select * from db_user limit " + page_num2 + "," + page_size2 + "";
            // console.log('--->',sql);
            db.query(sql, function (err, rows) {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询用户失败。',
                        err
                    })
                } else {
                    //as更换名称
                    db.query('select count(*) as total from db_user', function (error, among) {
                        if (error) {
                            resolve({
                                code: -1,
                                msg: '统计用户数量失败。',
                                error
                            })
                        } else {
                            resolve({
                                code: 200,
                                msg: "获取分页列表成功。",
                                result: rows,
                                page: {
                                    page_num: page_num,
                                    page_size: page_size,
                                    total: among[0]['total'] //查询表中的数量
                                }
                            })
                        }
                    })
                }
            })

        })
    },
    // 编写获取昵称方法
    // 参数：user_id
    nickName(user_id) {
        return new Promise((resolve, reject) => {
            // 查询用户
            db.query('select * from db_user where user_id="' + user_id + '"', (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询昵称失败。'
                    })
                } else {
                    // console.log(rows)
                    resolve({
                        code: 200,
                        msg: '查询昵称成功',
                        title: "hello",
                        user_name: rows[0] && rows[0]['user_name'],
                        user_avatar: rows[0] && rows[0]['user_avatar']
                    })
                }
            })
        })
    },
    // 编写统计用户人数方法
    all() {
        return new Promise((resolve, reject) => {
            db.query('select count(*) as total from db_user', function (error, among) {
                if (error) {
                    resolve({
                        code: -1,
                        msg: '统计用户数量失败。',
                        error
                    })
                } else {
                    resolve({
                        code: 200,
                        msg: "获取用户总人数成功。",
                        total: among[0]['total']
                    })
                }
            })

        })
    },
    // 编写获取用户详情方法
    // 参数：user_id
    detail(user_id) {
        return new Promise((resolve, reject) => {
            // 多字段模糊查询
            db.query("select * from db_user where user_id = '" + user_id + "'", (err, rows) => {
                if (err) {
                    resolve({
                        code: -1,
                        msg: '查询用户失败。',
                        err
                    })
                } else {
                    if (rows.length == 0) {
                        resolve({
                            code: -1,
                            msg: '没有该关键字匹配的题目。'
                        })
                    } else {
                        let user = {};
                        user['user_id'] = rows[0]['user_id'];
                        user['user_name'] = rows[0]['user_name'];
                        user['user_email'] = rows[0]['user_email'];
                        user['user_phone'] = rows[0]['user_phone'];
                        user['user_create_time'] = rows[0]['user_create_time'];
                        user['user_age'] = rows[0]['user_age'];
                        user['user_sex'] = rows[0]['user_sex'];
                        user['user_address'] = rows[0]['user_address'];
                        resolve({
                            code: 200,
                            msg: '查询用户成功。',
                            result: [user]
                        })
                    }
                }
            })
        })
    },
    // 编写删除文用户头像方法
    // 参数：
    deleteImg(user_avatar) {
        return new Promise((resolve, reject) => {
            console.log('xxx:',user_avatar)
            //通过slice方法，分割出图片前面的url地址
            let index = user_avatar.indexOf('upload')
            let temp_path = path.resolve(__dirname, '../../public', user_avatar.slice(index))
            console.log('--->',temp_path)
            // fs.unlink删除文件,path为图片文件地址
            fs.unlink(temp_path, function (error) {
                if (error) {
                    resolve({
                        code: -1,
                        msg: '删除用户头像失败。'
                    })
                }
                else {
                    //删除图片文件成功
                    resolve({
                        code: 200,
                        msg: '删除用户头像成功。'
                    })
                }
            })
        })
    },
}




